import React, { Component } from 'react';
import {
    View,
    Image,
    TextInput,
    ScrollView,
    StyleSheet,
    DeviceEventEmitter
} from 'react-native'
import KeyEvent from 'react-native-keyevent';
import Toast from 'react-native-root-toast';
import moment from 'moment'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { updateSaleList } from '../../actions/SaleAction';

import * as fetch from '../../utils/fetch'
import o from '../../components/o'
import Style from '../../utils/style/style'
import Loading from '../../views/loading';
import CellItem from '../../views/cellItem';
import CheckStateItem from '../../views/checkStateItem';
import CellTitleItem from '../../views/cellTitleItem';
import SerialsItem from '../../views/serialsItem';
import GoodItem from '../../views/goodItem';
import QrCode from '../../views/qrCode';
import PrimaryButton from '../../views/primaryButton';
import MsgModal from '../../components/modal/errorModal';
import ConfirmModal from '../../components/modal/confirmModal';
import RfidModule from '../../components/Rfid'
class Delivery extends Component {
    constructor(props) {
        super(props)
        this.state = {
            gooodsItem: null,
            disable: false,
            operaDisable: false,
            // codesStr: '',
            // codesArr: [],
            codesArr: ['00011FFF000001AAAA000998'],
            codesStr: '00011FFF000001AAAA000998',
            dataList: [],
            modal: {
                title: '',
                msg: '',
                visible: false
            },
            confirmModal: {
                title: '',
                msg: '',
                visible: false,
                confirmFuc: () => null,
            },
            repeatCodes: [],
        }
    }
    static navigationOptions = {
        title: '商品出库情况'
    }
    componentWillMount() {
        //通过使用DeviceEventEmitter模块来监听原生模块发送过来的事件
        DeviceEventEmitter.addListener('onInventoryTag', (Event) => {
            //盘存标签触发回调
            let result = Event.RfidResult;
            let codesArr = this.state.codesArr;
            for (let i = 0; i < codesArr.length; i++) {
                if (codesArr[i] == result) {
                    return;
                }
            }
            codesArr.push(result);
            this.setState({
                codesArr: codesArr,
            })
        });
        DeviceEventEmitter.addListener('onInventoryTagEnd', (Event) => {
            //盘存结束回调  
            const { codesArr } = this.state;
            if (codesArr.length > 20) {
                this._showModal("失败", "批量扫描个数请控制在20个以内");
                this.setState({
                    codesArr: [],
                    codesStr: '',
                })
            } else {
                this.setState({
                    codesStr: this.state.codesArr.join(',')
                })
            }
        });
        DeviceEventEmitter.addListener('onExeCMDStatus', (Event) => {
            this._showModal("失败", Event.ErrorMsg)
        })
        DeviceEventEmitter.addListener('getAllDevices', (Event) => {
            alert(Event.DevicesResult + "&&" + Event.PathResult);
        });
    }

    componentDidMount() {
        const { navigation } = this.props;
        const item = JSON.parse(navigation.getParam("item"));
        const SaleId = navigation.getParam("SaleId");
        const RecId = navigation.getParam("RecId");
        this.setState({
            gooodsItem: item,
            SaleId: SaleId,
            RecId: RecId,
            operaDisable: item.SNumber == item.outs ? true : false
        })
        KeyEvent.onKeyDownListener((evt) => {
            //监听手持机的扫码头按下等操作？
        })
        // RfidModule.getAllDevices();
        RfidModule.open();
        RfidModule.openCom();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (nextState.codesStr == this.state.codesStr && nextState.codesArr != this.state.codesArr) {
            //扫描标签即时回传过程中不调用render
            return false
        } else {
            return true
        }
    }

    _pressCode() {
        RfidModule.readRfid();
    }

    _compare() {
        const { codesArr, gooodsItem, codesStr } = this.state;
        if (!codesStr) { 
            this._showModal("失败", "请扫描二维码")
            return
         }
        if (codesArr.length > gooodsItem.SNumber) {
            this._showModal("失败","出库数超过销售数，请重新确认");
            this.setState({
                codesStr: '',
                codesArr: []
            })
            return;
        }
        //对比数据库已有序列号 1.序列号不存在 2.序列号已出库状态
        let params = {
            filter: 'CodeType eq 1 and GoodId eq ' + gooodsItem.GoodId
        }
        this.setState({
            disable: true
        })
        let repeatCodes = [];
        let notExistCodes = [].concat(codesArr);
        let BarCodeList = [];
        const { token } = this.props
        o(`erp_goodss?token=${token}`).filter(params.filter).get((res) => {
            if (res && res.length > 0) {
                for (let i = 0; i < res.length; i++) {
                    for (let j = 0; j < codesArr.length; j++) {
                        if (res[i].BarCode == codesArr[j]) {
                            if (res[i].State == 2) {
                                //已出库
                                repeatCodes.push(codesArr[j]);
                            } else {
                                BarCodeList.push(res[i]);
                            }
                            break;
                        }
                    }
                    // for (let l = 0; l < codesArr.length; l++) {
                    //     if (res[i].BarCode == codesArr[l]) {
                    //         //存在的排除
                    //         let diff = codesArr.length - notExistCodes.length;
                    //         let index = l == 0 ? 0 : Math.abs(l - diff)
                    //         notExistCodes.splice(index, 1);
                    //         break;
                    //     }
                    // }
                    for (let l = 0; l < notExistCodes.length; l++) {
                        if (res[i].BarCode == notExistCodes[l]) {
                            //存在的排除
                            notExistCodes.splice(l, 1);
                            break;
                        }
                    }
                }
                this.setState({
                    BarCodeList: BarCodeList,
                    repeatCodes: repeatCodes,
                    notExistCodes: notExistCodes
                })
            } else {
                this.setState({
                    notExistCodes: notExistCodes
                })
            }
            this._submit()
        })
    }

    _submit() {
        const { repeatCodes, notExistCodes } = this.state;
        if (repeatCodes && repeatCodes.length > 0) {
            this._showConfrimModal("失败", "以下序列号已出库:" + repeatCodes.join(','), () => { this._excludeExist() })
        } else if (notExistCodes && notExistCodes.length > 0) {
            this._showConfrimModal("失败", "以下序列号不存在:" + notExistCodes.join(','), () => { this._excludeNotExist() })
        }
        else {
            this._postData();
        }
    }

    _postData() {
        const { codesArr } = this.state;
        if (!codesArr || codesArr.length == 0) {
            this.setState({
                disable:false
            })
            return;
        }
        //序列号表更新状态和出库表新增  要求后端支持批量操作
        const BarCodeList = this.state.BarCodeList;
        const { TenantId, UserId } = this.props.userInfo;
        const { token } = this.props;
        for (let i = 0; i < BarCodeList.length; i++) {
            //出库表中新增
            let params_out = {
                BarCode: BarCodeList[i].BarCode,
                SaleId: this.state.gooodsItem.list_id,
                OperatorId: UserId,
                DeliveryTime: moment().format('YYYY-MM-DD HH:mm:ss'),
                TenantId: TenantId
            }
            console.log(params_out)
            o(`erp_out?token=${token}`).post(params_out).save(
                res => {

                },
                e => {
                    console.log(e)
                    Toast.show("出库失败", {
                        duration: Toast.durations.LONG,
                        position: Toast.positions.CENTER,
                    })
                    return;
                })

            // //商品序列号表中新增数据
            let params = {
                State: 2//2已出库
            }
            //按照文档的方式用patch 但是一直报400 不知道为啥 所以改用fetch
            fetch.fetchOdata('', 'erp_goodss', params, '', 'PUT', BarCodeList[i].RecId, token).then(() => {
                if (i == BarCodeList.length - 1) {
                    this._back()
                }
            }).catch(e => {
                console.log(e)
                Toast.show("出库失败", {
                    duration: Toast.durations.LONG,
                    position: Toast.positions.CENTER,
                })
            }
            )
        }
    }
    _back() {
        this.setState({
            disable: false
        })
        this._showModal("成功", "所有序列均已出库")
        const { SaleId, codesArr } = this.state;
        const { updateSaleList, navigation } = this.props;
        const param = { SaleId: SaleId, codesArr: codesArr };
        updateSaleList(param);
        navigation.pop(2)//back to list
    }
    _excludeExist() {
        //排除已存在的序列号
        let { repeatCodes, codesArr, notExistCodes } = this.state;
        for (let i = 0; i < repeatCodes.length; i++) {
            for (let j = 0; j < codesArr.length; j++) {
                if (repeatCodes[i] == codesArr[j]) {
                    codesArr.splice(j, 1);
                    break;
                }
            }
        }
        this.setState({
            codesArr: codesArr,
            codesStr: codesArr.join(',')
        })
        if (notExistCodes.length > 0) {
            this._showConfrimModal("失败", "以下序列号不存在:" + notExistCodes.join(','), () => { this._excludeNotExist() })
        } else {
                this._postData();
           
        }
    }

    _excludeNotExist() {
        //排除不存在的序列号
        this._hideConfirmModal();
        const { codesArr, notExistCodes } = this.state;
        for (let i = 0; i < notExistCodes.length; i++) {
            for (let j = 0; j < codesArr.length; j++) {
                if (notExistCodes[i] == codesArr[j]) {
                    codesArr.splice(j, 1);
                    break;
                }
            }
        }
        this.setState({
            codesArr: codesArr,
            codesStr: codesArr.join(',')
        })
            this._postData();
    }

    _renderSerials(item, index, length) {
        const noBorder = index == length - 1 ? true : false;
        return (
            <SerialsItem value={item.BarCode} noBorder={noBorder} />
        )
    }
    _renderModal() {
        return (
            <MsgModal
                title={this.state.modal.title}
                msg={this.state.modal.msg}
                visible={this.state.modal.visible}
                pressBtn={() => this._hideModal()}
            />
        )
    }
    _showModal(title, msg) {
        this.setState({
            modal: {
                title: title,
                msg: msg,
                visible: true
            }
        })
    }
    _hideModal() {
        this.setState({
            modal: {
                title: '',
                msg: '',
                visible: false
            }
        })
    }

    _showConfrimModal(title, msg, confirmFuc) {
        this.setState({
            confirmModal: {
                title: title,
                msg: msg,
                visible: true,
                confirmFuc: confirmFuc
            }
        })
    }
    _hideConfirmModal() {
        this.setState({
            confirmModal: {
                title: '',
                msg: '',
                visible: false
            }
        })
    }
    //确认模态框

    _renderConfirmModal() {
        return (
            <ConfirmModal
                title={this.state.confirmModal.title}
                msg={this.state.confirmModal.msg}
                btnCancelValue={"取消出库"}
                btnConfirmValue={"自动出库"}
                visible={this.state.confirmModal.visible}
                Cancel={() => this._hideConfirmModal()}
                Confirm={this.state.confirmModal.confirmFuc}
            />
        )
    }
    render() {
        let gooodsItem;
        if (this.state.gooodsItem) {
            gooodsItem = this.state.gooodsItem
        }
        const { operaDisable } = this.state
        return (
            <ScrollView style={styles.container}>
                <View style={Style.aic}>
                    <CellTitleItem title="商品" />
                    {
                        this.state.gooodsItem ? <GoodItem
                            source={gooodsItem.images[0]}
                            name={gooodsItem.Name}
                            key={gooodsItem.name}
                            showAngle={false}
                            detailList={gooodsItem.detailList}
                            pressItem={() => { return }}
                            noBorder={true}
                        /> : null
                    }
                    <View style={[Style.gap, Style.gapTop]} />
                    {
                        operaDisable ? null :
                            <View style={[{ width: Style.width }, Style.aic]}>
                                <QrCode pressCode={() => this._pressCode()} />
                                <View style={styles.textWrap}>
                                    <TextInput multiline={true} placeholder="扫描添加标签" editable={false} underlineColorAndroid="transparent" style={styles.textInput} value={this.state.codesStr}  ></TextInput>
                                </View>
                                <PrimaryButton title="立即出库" submit={() => this._compare()} disable={this.state.disable} />
                                <View style={styles.mt}></View>
                            </View>
                    }

                    {
                        gooodsItem && gooodsItem.salelist_out.length > 0 ?
                            <View>
                                <CellTitleItem title="已出库序列号" />
                                <View>
                                    {
                                        gooodsItem.salelist_out.map((item, index) => this._renderSerials(item, index, gooodsItem.salelist_out.length))
                                    }
                                </View>
                            </View>
                            : null
                    }

                    <View style={Style.bottom}></View>
                    {this._renderModal()}
                    {this._renderConfirmModal()}
                </View>
            </ScrollView>

        )
    }
}

const styles = StyleSheet.create({
    container: {
        width: Style.width,
        height: Style.ViewHeightD,
        backgroundColor: '#fff',
    },
    mt: {
        marginTop: 20
    },
    textWrap: {
        width: Style.width,
        height: 150,
        borderColor: '#e5e5e5',
        borderStyle: 'solid',
        borderTopWidth: 1,
        borderBottomWidth: 1,
        marginBottom: 20,
    },
    textInput: {
        padding: 10,
    },
})

export default connect(
    state => ({ userInfo: state.User.userInfo, token: state.User.token }),
    dispatch => ({
        updateSaleList: bindActionCreators(updateSaleList, dispatch),
    })
)(Delivery)